<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { useLayout } from "@/layout/hooks/useLayout";
import { useNav } from "@/layout/hooks/useNav";
import { getTopMenu, initRouter } from "@/router/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { AES_Decrypt, AES_Encrypt } from "@/utils/crypto";
import { message } from "@/utils/message";
import type { FormInstance } from "element-plus";
import { h, onBeforeUnmount, onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import Motion from "./utils/motion";
import { loginRules } from "./utils/rule";

import { upUser } from "@/api/system/user";
import { chagneLoginStatus } from "@/api/user";
import { addDialog } from "@/components/ReDialog";
import AddUpTeacher from "@/components/common/AddUpTeacher";

import { removeToken } from "@/utils/auth";
import Cookies from "js-cookie";

import bgLogo from "@/assets/login/logo.png";
import bgLogo2 from "@/assets/login/logo2.png";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const rememberPwd = ref(false);

const { initStorage } = useLayout();
initStorage();

const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title } = useNav();

const ruleForm = reactive({
  username: "",
  password: ""
});

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByUsername({
          number: ruleForm.username,
          password: ruleForm.password
        })
        .then(async res => {
          if (res.success) {
            if (rememberPwd.value) {
              Cookies.set(
                "art_accountInfo",
                AES_Encrypt(JSON.stringify(ruleForm))
              );
            }
            if (res.data.userType == 0 && res.data.firstLogin == 1) {
              loginSuccess(res.data);
            } else {
              if (res.data.firstLogin == 1) {
                await chagneLoginStatus();
              }
              initRouter().then(data => {
                let toPath = getTopMenu(true)?.path || "";
                if (!toPath) {
                  return message("当前用户没有配置页面，请联系管理员", {
                    type: "warning"
                  });
                }
                router.push(toPath).then(() => {
                  message("登录成功", { type: "success" });
                });
              });
            }
          } else {
            message("登录失败", { type: "error" });
          }
        })
        .finally(() => (loading.value = false));
    }
  });
};

/** 登录成功 */
const formRef = ref();
const loginSuccess = async data => {
  addDialog({
    title: "修改信息",
    props: {
      id: data.id,
      optType: 1
    },
    width: "1000px",
    fullscreenIcon: true,
    closeOnClickModal: false,
    sureBtnLoading: true,
    draggable: true,
    contentRenderer: () => h(AddUpTeacher, { ref: formRef }),
    beforeSure: (done, { options, closeLoading }) => {
      const FormRef = formRef.value.getRef();
      const formVal = formRef.value.getFormVal();
      FormRef.validate(async valid => {
        if (valid) {
          await upUser(formVal);
          await chagneLoginStatus();
          // 获取后端路由
          initRouter().then(() => {
            let toPath = getTopMenu(true)?.path || "";
            if (!toPath) {
              message("当前用户没有配置页面，请联系管理员", {
                type: "warning"
              });
              return;
            }
            router.push(toPath).then(() => {
              message("登录成功", { type: "success" });
            });
          });
          done();
        } else {
          closeLoading();
        }
      });
    },
    beforeCancel: done => {
      removeToken();
      done();
    },
    close: () => {
      removeToken();
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    onLogin(ruleFormRef.value);
  }
}

watch(rememberPwd, newVal => {
  if (!newVal) {
    // 清空存储的值
    Cookies.remove("art_accountInfo");
  }
});
const getRememberPwd = () => {
  let accountInfo = Cookies.get("art_accountInfo");
  if (accountInfo) {
    let addcountObj = JSON.parse(AES_Decrypt(accountInfo));
    ruleForm.username = addcountObj.username;
    ruleForm.password = addcountObj.password;
    rememberPwd.value = true;
  } else {
    rememberPwd.value = false;
  }
};

onMounted(() => {
  getRememberPwd();
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <div class="login-container">
      <div class="wave">
        <!-- <div class="login-title">
          <img :src="bgLogo" width="70" height="70" alt="" class="bg-logo" />
          <img :src="bgTitle" width="130" height="37" alt="" />
        </div> -->
      </div>
      <div class="login-box">
        <img :src="bgLogo" width="120" height="120" alt="" class="bg-logo" />
        <img :src="bgLogo2" width="300" height="300" alt="" class="bg-logo2" />
        <div class="login-form">
          <!-- <avatar class="avatar" /> -->
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入工号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  placeholder="请输入工号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password" class="!mb-2">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="请输入密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="" class="!mb-0">
                <el-checkbox v-model="rememberPwd" label="Remember Me">
                  <div>记住密码</div>
                </el-checkbox>
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4 !font-bold !text-lg btn-login"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.scss");
</style>
